#coding=UTF-8
import requests
import json

#请求头："Content-Type": "application/json"请求主题类型为json
hearders = {
    "Content-Type": "application/json"
}
#请求主题，其中包含了所需要的认证信息
body = {
    "auth": {
        "identity": {
            "methods": ["password"],
            "password": {
                "user": {
                    "domain": {"name": "demo"},
                    "name": "admin",
                    "password": "000000"
                }
            }
        },
        "scope": {
            "project": {
                "domain": {"name": "demo"},
                "name": "admin"
            }
        }
    }
}
#keystone rustful-api 端点url
keystone_url="http://192.168.100.10:5000/v3/auth/tokens?nocatalog"
#定义一个方法，方便其他模块调用
#使用方法：
#import keystone
#keystone_s=keystone.getToken()
#keystone_s['token']
#keystone_s['project_id']
def getToken(url="http://192.168.100.10:5000/v3/auth/tokens?nocatalog"):
    # 发送post请求，代码中的“json.dumps”是为了把body变量编码成json。
    req = requests.post(keystone_url, headers=hearders, data=json.dumps(body))
    # 从返回的相应头中获取信息
    project_id = req.json()['token']['project']['id']
    token = req.headers['X-Subject-Token']
    # 打印返回的数据
    print(json.dumps(req.json(), sort_keys=True, indent=4))
    return {"token":token,"project_id":project_id}

if __name__=="__main__":
    print(getToken(keystone_url))